/*
 * CorregimientosBusquedaFrame.java
 *
 * Created on 27 de abril de 2008, 03:11 PM
 */

package org.contabilidad.municipios;

import org.mybeans.Sesion;
import org.mybeans.CorregimientosBeans;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author  avbravo
 */
public class CorregimientosBusquedaFrame extends javax.swing.JFrame {
  Sesion sesion;
    int fila = -1;
    DefaultTableModel modelo;
    CorregimientosBeans corregimientosBeans;
    /** Creates new form CorregimientosBusquedaFrame */
    public CorregimientosBusquedaFrame() {
        initComponents();
          /*
             * Fondo
             */

            
              
             

             
             

            /*
             * fin del fondo
             */
        sesion = new Sesion();
        corregimientosBeans = new CorregimientosBeans();
            String sql = "select * from corregimients  where idmunicipio = '" + sesion.getIdmunicipio() + "' order by corregimiento";
    CargarTodosRegistros(sql);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCorregimiento = new javax.swing.JTextField();
        jButtonBuscar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButtonVerTodos = new javax.swing.JButton();
        jTextFieldIdCorregimiento = new javax.swing.JTextField();
        jButtonBuscarCodigo = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldNuevoNombre = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Busqueda de Corregimientos");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Corregimientos");

        jTextFieldCorregimiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCorregimientoActionPerformed(evt);
            }
        });

        jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/consultar.png"))); // NOI18N
        jButtonBuscar.setToolTipText("Consultar");
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jLabel1.setText("Codigo");

        jButtonVerTodos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/view.png"))); // NOI18N
        jButtonVerTodos.setToolTipText("Ver Todos");
        jButtonVerTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVerTodosActionPerformed(evt);
            }
        });

        jTextFieldIdCorregimiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIdCorregimientoActionPerformed(evt);
            }
        });

        jButtonBuscarCodigo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/consultar.png"))); // NOI18N
        jButtonBuscarCodigo.setToolTipText("Consultar");
        jButtonBuscarCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarCodigoActionPerformed(evt);
            }
        });

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Grupo"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel3.setText("Nuevo Nombre");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButton1.setToolTipText("Actualizar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/view.png"))); // NOI18N
        jButton2.setToolTipText("Ver Todos a nivel nacional");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
                .addGap(136, 136, 136))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(1, 1, 1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonVerTodos, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTextFieldCorregimiento)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextFieldIdCorregimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonBuscarCodigo)))
                        .addGap(18, 18, 18)
                        .addComponent(jButtonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(75, 75, 75))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldNuevoNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(60, 60, 60))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldCorregimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldIdCorregimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jButtonBuscarCodigo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jTextFieldNuevoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButtonVerTodos, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                            .addComponent(jButtonRegresar, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed
 
BuscarCorregimiento();
}//GEN-LAST:event_jButtonBuscarActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed
 
    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonVerTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerTodosActionPerformed
BuscarTodos();
    
}//GEN-LAST:event_jButtonVerTodosActionPerformed

private void jButtonBuscarCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarCodigoActionPerformed
 
    BuscarCodigo();
    
}//GEN-LAST:event_jButtonBuscarCodigoActionPerformed

private void jTextFieldCorregimientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCorregimientoActionPerformed
 
    BuscarCorregimiento();
}//GEN-LAST:event_jTextFieldCorregimientoActionPerformed

private void jTextFieldIdCorregimientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIdCorregimientoActionPerformed
 
    BuscarCodigo();
}//GEN-LAST:event_jTextFieldIdCorregimientoActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
     try {
         String idcorregimiento= jTextFieldIdCorregimiento.getText();
if (idcorregimiento.equals("") || idcorregimiento == null){
     JOptionPane.showMessageDialog(this, "Ingrese el nombre del corregimiento", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
     return;
}
String corregimientonuevo= jTextFieldNuevoNombre.getText();
if (corregimientonuevo.equals("") || corregimientonuevo == null){
     JOptionPane.showMessageDialog(this, "Ingrese el nombre del corregimiento", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
     return;
}

        String sql = "update corregimients set corregimiento = ? where idcorregimiento =?";
        PreparedStatement prest = sesion.con.prepareStatement(sql);

        prest.setString(1, corregimientonuevo);
        prest.setString(2,idcorregimiento);
        

        int count = prest.executeUpdate();
        sesion.con.close();
        JOptionPane.showMessageDialog(this, "Corregimiento actualizado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        jTextFieldCorregimiento.setText(corregimientonuevo);
       BuscarTodos();
         

    } catch (Exception ex) {
        System.out.println("Error" + ex);
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    BuscarTodosGlobal();
}//GEN-LAST:event_jButton2ActionPerformed
private void BuscarTodos(){
    String sql = "select * from corregimients  where idmunicipio = '" + sesion.getIdmunicipio() + "' order by corregimiento";
    CargarTodosRegistros(sql);
}

private void BuscarTodosGlobal(){
    String sql = "select * from corregimients  order by corregimiento";
    CargarTodosRegistros(sql);
}
private void BuscarCorregimiento(){
        try {


        String corregimiento = (String) this.jTextFieldCorregimiento.getText();
        String sql = "select * from corregimients  where corregimients.corregimiento like '%" + corregimiento + "%' and idmunicipio = '" + sesion.getIdmunicipio() + "' order by corregimiento";
        CargarTodosRegistros(sql);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}

private void BuscarCodigo(){
    try {


        String idcorregimiento = (String) this.jTextFieldIdCorregimiento.getText();
        String sql = "select * from corregimients  where corregimients.idcorregimiento like '%" + idcorregimiento + "%'  order by corregimiento";
        CargarTodosRegistros(sql);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}
 private void CargarTodosRegistros(String sql) {
        try {

            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            PreparedStatement psquery = sesion.con.prepareStatement(sql);
            ResultSet rs = psquery.executeQuery();

            modelo = new DefaultTableModel();
            // Creamos las columnas.
            modelo.addColumn("codigo");
            modelo.addColumn("corregimiento");
            modelo.addColumn("idmunicipio");


// Bucle para cada resultado en la consulta
            while (rs.next()) {
                // Se crea un array que será una de las filas de la tabla.
                Object[] fila = new Object[3]; // Hay tres columnas en la tabla

                fila[0] = rs.getString("idcorregimiento");
                fila[1] = rs.getString("corregimiento");
                fila[2] = rs.getString("idmunicipio");
                modelo.addRow(fila);

            }
            this.jTable1.setModel(modelo);
            jTable1.setVisible(true);
            //aris++
            this.jTable1.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent e) {

                    fila = jTable1.rowAtPoint(e.getPoint());
                    int columna = jTable1.columnAtPoint(e.getPoint());
                    if ((fila > -1) && (columna > -1)) {
                        jTextFieldIdCorregimiento.setText(String.valueOf(jTable1.getValueAt(fila, 0)));
                        jTextFieldCorregimiento.setText(String.valueOf(jTable1.getValueAt(fila, 1)));
                        jTextFieldNuevoNombre.setText(String.valueOf(jTable1.getValueAt(fila, 1)));
                        String IdMunicipio = String.valueOf(jTable1.getValueAt(fila, 2));
                        corregimientosBeans.setIdCorregimiento((String) jTextFieldIdCorregimiento.getText());
                        corregimientosBeans.setCorregimiento((String) jTextFieldCorregimiento.getText());
                        corregimientosBeans.setIdMunicipio(IdMunicipio);

                    }
                }
            });

            TableColumn column = jTable1.getColumnModel().getColumn(1);
            column.setPreferredWidth(200);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CorregimientosBusquedaFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonBuscarCodigo;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JButton jButtonVerTodos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldCorregimiento;
    private javax.swing.JTextField jTextFieldIdCorregimiento;
    private javax.swing.JTextField jTextFieldNuevoNombre;
    // End of variables declaration//GEN-END:variables

}
